package db

import (
	"strings"

	"gitee.com/miajio/go-generator-mysql/pkg/common"
)

type DescTable struct {
	Field   string  `db:"Field"`   // 字段名称
	Type    string  `db:"Type"`    // 字段类型
	Null    string  `db:"Null"`    // 是否允许为空
	Key     string  `db:"Key"`     // 是否key
	Default *string `db:"Default"` // 默认值
	Comment *string `db:"Comment"` // 注释
}

// RowToColumn 字段转结构体参数
// 依据hump判定是否驼峰算法进而生成golang结构体
func (row *DescTable) RowToColumn(hump bool) *ColumnModel {
	var result ColumnModel
	result.Tag = make(map[string]string)

	if hump {
		result.Name = common.StringUtil.Hump(row.Field, true)
	} else {
		result.Name = common.StringUtil.UpInitials(row.Field)
	}

	tp := row.Type

	if strings.Index(tp, " ") > 0 {
		tp = strings.Split(tp, " ")[0]
	}

	tp = dbTypeToStructType(tp)
	if strings.Contains(row.Type, "unsigned") {
		tp = "u" + tp
	}

	result.Type = tp

	if row.Null == "YES" {
		result.IsPoint = true
	}
	result.Tag["db"] = row.Field

	result.Annotation = row.Comment
	return &result
}

const (
	descSql = `SELECT COL.COLUMN_NAME    as 'Field',
					COL.COLUMN_TYPE    	 as 'Type',
					COL.COLUMN_KEY       as 'Key',
					COL.COLUMN_DEFAULT   as 'Default',
					COL.IS_NULLABLE      as 'Null',
					COL.COLUMN_COMMENT   as 'Comment'
				FROM INFORMATION_SCHEMA.COLUMNS COL
					WHERE COL.TABLE_NAME = ?`
)

func DescTableFunc(table string) ([]DescTable, error) {
	db, err := DBConnect()
	if err != nil {
		return nil, err
	}
	var st []DescTable
	if err = db.Select(&st, descSql, table); err != nil {
		return nil, err
	}
	defer db.Close()

	return st, nil
}
